<script setup lang="ts">
import { computed, ref } from 'vue'
import { message } from '@/utils/message'
import { ModalShowType, ModalShowTitle } from '@/types/common'
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElSelect,
  FormInstance,
} from 'element-plus'
import { useStorage } from '@/hooks/useStorage'
import { appAdd, getDeptList, getAppDetail, editAdd } from '@/api/app-list/app-list'
import { ElMessageBox } from 'element-plus'
import useDictStore from '@/store/modules/dict'

const props = defineProps<{
  modalShow: ModalShowType
  termId: string | null
  onSearch?: () => Promise<void>
  onRead?: () => Promise<void>
}>()

const emit = defineEmits<{
  (e: 'update:modalShow', type: ModalShowType): void
}>()

const modalShow = computed({
  get() {
    return props.modalShow
  },
  set(value) {
    emit('update:modalShow', value)
  },
})
const ruleFormRef = ref<FormInstance>()

const formData = ref({
  costId: undefined,
  projectId: undefined,
  appName: '',
  appAttribute: '',
  appLabel: '',
  appIntroduce: '',
  remark: '',
  deptId: '',
  appContact: '',
  appContactPhone: '',
})

const projectInfo = ref({})
const projectLoading = ref(false)
const { app_type } = useDictStore().getDicts('app_type')
const [loading, toggleLoading] = useToggle(false)

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const ok = await formEl.validate()
  if (!ok) return

  toggleLoading(true)
  try {
    if (modalShow.value === ModalShowType.New) {
      await appAdd({ ...formData.value })
    } else {
      await editAdd({ ...formData.value, appId: props.termId })
    }
  } finally {
    toggleLoading(false)
  }
  // if (modalShow.value === ModalShowType.New) {
  //   await costMgtAdd({ ...formData.value });
  // } else {
  //   await costMgtUpdate({ ...formData.value });
  // }
  message('提交成功', { type: 'success' })
  resetFields()
  storageData.value = null
  modalShow.value = ModalShowType.Hide
  await props.onSearch()
}

const storageData = useStorage(
  computed(
    () => window.location.href + (props.modalShow === ModalShowType.New ? 'new' : props.termId)
  )
)

const rules = {
  appName: [{ required: true, message: '请输入', trigger: 'change' }],
  appAttribute: [{ required: true, message: '请输入', trigger: 'change' }],
  customerDeptName: [{ required: true, message: '请输入', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择', trigger: 'change' }],
  appContact: [{ required: true, message: '请输入', trigger: 'change' }],
  appContactPhone: [{ required: true, message: '请输入', trigger: 'change' }],
}

const deptList = ref<{ deptName: string; deptId: number }[]>([])
const selectLoading = ref<boolean>(false)

async function remoteMethod() {
  selectLoading.value = true

  const { code, data } = await getDeptList()
  selectLoading.value = false
  if (code == 200) {
    deptList.value = data
  }
}

const resetFields = () => {
  ruleFormRef.value.resetFields()
  formData.value = {
    costId: undefined,
    projectId: undefined,
    appName: '',
    appAttribute: '',
    appLabel: '',
    appIntroduce: '',
    remark: '',
    deptId: '',
    appContact: '',
    appContactPhone: '',
  }
}
const onOpen = async () => {
  projectLoading.value = true
  await remoteMethod()
  if (storageData.value !== null) {
    formData.value = storageData.value.formData
  } else {
    if (modalShow.value === ModalShowType.New) {
      resetFields()
    } else {
      const { data } = await getAppDetail(props.termId)
      formData.value = {
        ...data,
      }
    }
  }
  projectLoading.value = false
}

const beforeCloseDialog = () => {
  if (modalShow.value == ModalShowType.New) {
    ElMessageBox.confirm('即将关闭此弹窗，是否将当前编辑内容保存草稿？', '确认关闭弹窗', {
      distinguishCancelAndClose: true,
      confirmButtonText: '保存草稿',
      cancelButtonText: '丢弃',
    })
      .then(() => {
        //保存草稿
        storageData.value = {
          projectInfo: projectInfo.value,
          formData: formData.value,
        }
        onClose()
      })
      .catch((action) => {
        if (action == 'cancel') {
          // 丢弃
          storageData.value = null
          onClose()
        }
      })
  } else {
    onClose()
  }
}

const onClose = () => {
  modalShow.value = ModalShowType.Hide
  resetFields()
}
</script>

<template>
  <el-drawer
    :close-on-click-modal="false"
    :title="ModalShowTitle.get(modalShow) + '应用'"
    class="common-dialog"
    :model-value="modalShow !== ModalShowType.Hide"
    :before-close="beforeCloseDialog"
    size="50%"
    @open="onOpen"
    @closed="
      async () => {
        if (props.onRead !== undefined) await props.onRead()
      }
    "
  >
    <el-form
      ref="ruleFormRef"
      v-loading="projectLoading"
      :model="formData"
      :rules="rules"
      label-width="130px"
      element-loading-text="正在获取应用信息..."
      :disabled="props.modalShow === ModalShowType.View"
    >
      <section-info>
        <template #title>应用信息</template>
        <el-form-item label="应用名称" prop="appName">
          <el-input
            v-model="formData.appName"
            placeholder="请输入应用名称"
            show-word-limit
            :maxlength="50"
          />
        </el-form-item>
        <el-form-item label="应用属性" prop="appAttribute">
          <el-select v-model="formData.appAttribute" placeholder="请选择应用属性">
            <el-option
              v-for="item in app_type"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用简介" prop="appIntroduce">
          <el-input
            v-model="formData.appIntroduce"
            :disabled="props.modalShow === ModalShowType.View"
            type="textarea"
            placeholder="输入内容"
            :maxlength="300"
            show-word-limit
            :rows="6"
          />
        </el-form-item>
        <el-form-item label="应用标签" prop="appLabel">
          <el-input
            v-model="formData.appLabel"
            placeholder="请输入"
            show-word-limit
            :maxlength="50"
          />
        </el-form-item>
      </section-info>
      <section-info>
        <template #title>联系人信息</template>
        <el-form-item label="归属部门" prop="deptId">
          <el-select
            v-model="formData.deptId"
            :disabled="props.modalShow === ModalShowType.View"
            filterable
            placeholder="请选择归属部门"
          >
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :value="item.deptId"
              :label="item.deptName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用联系人" prop="appContact">
          <el-input
            v-model="formData.appContact"
            placeholder="请输入"
            show-word-limit
            :maxlength="12"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="appContactPhone">
          <el-input
            v-model="formData.appContactPhone"
            placeholder="请输入联系电话"
            show-word-limit
            :maxlength="11"
          />
        </el-form-item>
      </section-info>
    </el-form>
    <template #footer>
      <template v-if="modalShow !== ModalShowType.View">
        <el-button
          v-if="modalShow == ModalShowType.New"
          type="primary"
          @click="
            () => {
              storageData.value = {
                formData: formData,
              }
              modalShow = ModalShowType.Hide
            }
          "
        >
          保存草稿
        </el-button>
        <el-button @click="beforeCloseDialog">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm(ruleFormRef)">
          {{ modalShow === ModalShowType.New ? '创建应用' : '确认' }}
        </el-button>
      </template>
      <el-button v-if="modalShow === ModalShowType.View" @click="modalShow = ModalShowType.Hide">
        关闭
      </el-button>
    </template>
  </el-drawer>
</template>
